package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.user.app.UserService;
import crp.core.user.domain.models.UserEntity;
import crp.services.api.graphql.models.UserPayload;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

@ApplicationScoped
public class UserFetcher {
    private final UserService userService;

    @Inject
    public UserFetcher(UserService userService) {
        this.userService = userService;
    }

    public List<UserPayload> fetch(List<String> ids) {
        Map<String, UserPayload> mapping = C2.map(userService.searcher().byIds(ids),
                UserEntity::getId,
                UserPayload::of);
        return C2.list(ids, mapping::get);
    }

    public <S> List<UserPayload> fetch(List<S> sources, Function<S, String> idMapper) {
        Set<String> ids = C2.set(sources, idMapper, Objects::nonNull);
        Map<String, UserPayload> mapping = C2.map(userService.searcher().byIds(ids),
                UserEntity::getId,
                UserPayload::of);
        return C2.list(sources, source -> Optional.ofNullable(idMapper.apply(source))
                .map(mapping::get)
                .orElse(null));
    }
}